package com.xx.pmis.web.util;

import java.awt.Color;
import java.awt.Font;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartRenderingInfo;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.entity.StandardEntityCollection;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.servlet.ServletUtilities;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.ui.TextAnchor;

import com.xx.pmis.model.Account;
import com.xx.pmis.model.util.Chart;
import com.xx.pmis.services.AccountService;

public class ChartAccount extends PMISBaseUtil {
	private static final Log log = LogFactory.getLog(ChartAccount.class);

	AccountService accountService = getPMISServices().getAccountService();

	/**
	 * 柱状图
	 */
	@SuppressWarnings("deprecation")
	public String generateBarChart(String title, HttpSession session, PrintWriter pw, int w, int h) {
		title = title.trim();
		String s[] = title.split("@");
		String filename = null;
		CategoryDataset dataset = getCategoryDataSet();
		JFreeChart chart = ChartFactory.createBarChart3D(s[0], // 图表标题
				s[1], // 目录轴的显示标签
				s[2], // 数值轴的显示标签
				dataset, // 数据集
				PlotOrientation.VERTICAL, // 图表方向：水平、垂直
				true, // 是否显示图例(对于简单的柱状图必须是false)
				false, // 是否生成工具
				false // 是否生成URL链接
				);
		chart.setBackgroundPaint(new Color(255, 255, 255));
		chart.setBorderVisible(false);
		CategoryPlot plot = chart.getCategoryPlot();

		CategoryAxis domainAxis = plot.getDomainAxis();// x轴
		ValueAxis numberaxis = plot.getRangeAxis(); // y轴
		plot.setForegroundAlpha(1f);

		BarRenderer barrenderer = (BarRenderer) plot.getRenderer();

		// 显示每个柱的数值，并修改该数值的字体属性
		// BarRenderer3D renderer = new BarRenderer3D();
		barrenderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
		barrenderer.setBaseItemLabelsVisible(true);
		barrenderer.setBaseFillPaint(Color.decode("#799AE1"));
		barrenderer.setMaximumBarWidth(0.03); // 设置柱状图的width

		barrenderer.setItemLabelPaint(Color.decode("#000000"));
		barrenderer.setItemLabelFont(new Font("宋体", Font.BOLD, 6));
		// 默认的数字显示在柱子中，通过如下两句可调整数字的显示
		// 注意：此句很关键，若无此句，那数字的显示会被覆盖，给人数字没有显示出来的问题
		barrenderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12,
				TextAnchor.BASELINE_LEFT));
		barrenderer.setItemLabelAnchorOffset(-20D);
		// 设置每个地区所包含的平行柱的之间距离
		barrenderer.setItemMargin(0.00000000003);
		// 改变柱子的颜色
		// 设置柱子宽度
		barrenderer.setMaximumBarWidth(0.0080000000000001D);
		// 设置柱子高度
		barrenderer.setMinimumBarLength(0.2);
		// 设置每个地区所包含的平行柱的之间距离
		barrenderer.setItemMargin(0.0005);

		TextTitle t = chart.getTitle();
		t.setFont(new Font("宋体", Font.BOLD, 12));// 标题文字

		domainAxis.setLabelFont(new Font("宋体", Font.PLAIN, 14));// x轴标题文字
		domainAxis.setTickLabelFont(new Font("宋体", Font.PLAIN, 12));// x轴坐标上文字
		numberaxis.setLabelFont(new Font("宋体", Font.PLAIN, 14));// y轴标题文字
		numberaxis.setTickLabelFont(new Font("宋体", Font.PLAIN, 12));// y轴坐标上文字

		chart.getLegend().setItemFont(new Font("宋体", Font.PLAIN, 12));// 图例文字

		try {
			// 得到chart的保存路径
			ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
			filename = ServletUtilities.saveChartAsPNG(chart, w, h, info, session);
			// 使用printWriter将文件写出
			ChartUtilities.writeImageMap(pw, filename, info, true);
			pw.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return filename;
	}

	/**
	 * 获取一个柱状图数据集对象
	 * 
	 * @return
	 */
	private CategoryDataset getCategoryDataSet() {
		DefaultCategoryDataset dataset = new DefaultCategoryDataset();
		List<Chart> list = buildCategoryDataset();
		Iterator<?> it = list.iterator();
		while (it.hasNext()) {
			Chart chart = (Chart) it.next();
			dataset.addValue(chart.getTotal(), chart.getParam2(), chart.getParam1());
		}
		return dataset;
	}

	/**
	 * 组装柱状图数据集
	 * 
	 * @return
	 */
	public List<Chart> buildCategoryDataset() {
		List<Chart> listChart = new ArrayList<Chart>();
		String currentYear = CurrentDate.currentYear();
		String currentDate = CurrentDate.currentDate();
		String currentMonth = currentDate.substring(5, 7);
		int month = Integer.parseInt(currentMonth);
		// String currentYear = "2011";
		int year = Integer.parseInt(currentYear);
		// int month = 8;
		for (int j = 2; j >= 0; j--) {

			for (int i = month + 1; i <= 12; i++) {
				// 柱状图实体
				Chart chart = new Chart();
				double total1 = 0.00;// 收入
				double total2 = 0.00;// 支出
				double total3 = 0.00;// 余额
				List<?> listAccount = null;
				try {
					listAccount = accountService.getAllAccountByCondition(" where year(accountDate)='"
							+ String.valueOf(year - 1) + "' and month(accountDate)='" + String.valueOf(i) + "'");
				} catch (Exception e) {
					log.info("组装饼图数据集时，根据商店ID查询礼品异常！" + e.toString());
				}
				Iterator<?> itAccount = listAccount.iterator();
				while (itAccount.hasNext()) {
					Account account = (Account) itAccount.next();
					if (account.getIncrease().equals("")) {
						// 支出
						total2 = total2 + Double.parseDouble(replaceAllRMB(account.getReduction()));
					}
					if (account.getReduction().equals("")) {
						// 收入
						total1 = total1 + Double.parseDouble(replaceAllRMB(account.getIncrease()));
					}
				}
				// 期初余额
				total3 = total1 - total2;
				chart.setParam1(String.valueOf(i) + "月");
				if (j == 2) {
					chart.setTotal(total1);
					chart.setParam2("收入");
				} else if (j == 1) {
					chart.setTotal(total2);
					chart.setParam2("支出");
				} else {
					chart.setTotal(total3);
					chart.setParam2("期初余额");
				}
				listChart.add(chart);
			}
		}
		// 当年的数据
		for (int k = 2; k >= 0; k--) {

			for (int i = 1; i <= month; i++) {
				// 柱状图实体
				Chart chart = new Chart();
				double total1 = 0.00;// 收入
				double total2 = 0.00;// 支出
				double total3 = 0.00;// 余额
				List<?> listAccount = null;
				try {
					listAccount = accountService.getAllAccountByCondition(" where year(accountDate)='" + currentYear
							+ "' and month(accountDate)='" + String.valueOf(i) + "'");
				} catch (Exception e) {
					log.info("组装饼图数据集时，根据商店ID查询礼品异常！" + e.toString());
				}
				Iterator<?> itAccount = listAccount.iterator();
				while (itAccount.hasNext()) {
					Account account = (Account) itAccount.next();
					if (account.getIncrease().equals("")) {
						// 支出
						total2 = total2 + Double.parseDouble(replaceAllRMB(account.getReduction()));
					}
					if (account.getReduction().equals("")) {
						// 收入
						total1 = total1 + Double.parseDouble(replaceAllRMB(account.getIncrease()));
					}
				}
				// 期初余额
				total3 = total1 - total2;
				chart.setParam1(String.valueOf(i) + "月");
				if (k == 2) {
					chart.setTotal(total1);
					chart.setParam2("收入");
				} else if (k == 1) {
					chart.setTotal(total2);
					chart.setParam2("支出");
				} else {
					chart.setTotal(total3);
					chart.setParam2("期初余额");
				}
				listChart.add(chart);
			}
		}

		return listChart;
	}

	// 把收入支出中的"-"、"￥"剔除掉
	public static String replaceAllRMB(String arg) {
		arg = arg.replaceAll("￥", "").replace("-", "");
		return arg;

	}

}
